#include "formnewcard.h"
#include "ui_formnewcard.h"
#include "xmlsyntaxhighlighter.h"

#include <QDebug>

FormNewCard::FormNewCard(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormNewCard)
{
    ui->setupUi(this);
    connectAll2All();

    ui->PriceSelectWidget->setCheckBoxesVisible(false);
    ShowCreatureProperties(false);
    ui->btnSave->setVisible(false);
    new XmlSyntaxHighlighter(ui->txtCustomText->document());
}

FormNewCard::~FormNewCard()
{
    delete ui;
}

void FormNewCard::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void FormNewCard::ShowCreatureProperties(bool visible)
{
    ui->lblLife->setVisible(visible);
    ui->spnLife->setVisible(visible);
    ui->chkLifeX->setVisible(visible);
    ui->lblDamage->setVisible(visible);
    ui->spnDamage->setVisible(visible);
    ui->chkDamageX->setVisible(visible);

    ui->gbxCreatrueProperties->setVisible(visible);
    ui->gbxProtects->setVisible(visible);
}

void FormNewCard::connectAll2All()
{
    connect(ui->ButtonAddNewAdditionalAbility, SIGNAL(clicked()), this, SLOT(SlotAddNewAdditionalAbility()));
    connect(ui->listWidgetAdditionalAbilities, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(SlotEditAdditionalAbility(QModelIndex)));

    connect(ui->textCardName, SIGNAL(textChanged(QString)), this, SLOT(textCardNameChanged(QString)));
    connect(ui->textCardDescription, SIGNAL(textChanged(QString)), this, SLOT(textCardDescriptionChanged(QString)));

    connect(ui->cmbCardSubType, SIGNAL(editTextChanged(QString)), this, SLOT(cmbCardSubTypeChanged(QString)));
    connect(ui->cmbCardType, SIGNAL(currentIndexChanged(QString)), this, SLOT(cmbCardTypeChanged(QString)));

    connect(ui->spnLife, SIGNAL(valueChanged(QString)), this, SLOT(spnLifeChanged(QString)));
    connect(ui->spnDamage, SIGNAL(valueChanged(QString)), this, SLOT(spnDamageChanged(QString)));
    connect(ui->chkDamageX, SIGNAL(clicked(bool)), this, SLOT(chkDamageXChanged(bool)));
    connect(ui->chkLifeX, SIGNAL(clicked(bool)), this, SLOT(chkLifeXChanged(bool)));

    connect(ui->chkHaste, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkEcho, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkFear, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkFirstStrike, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkArtefact, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkFlying, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkTrample, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkVigilance, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkDefender, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkCantBlock, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkTapped, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));
    connect(ui->chkThreshold, SIGNAL(clicked(bool)), this, SLOT(chkPropertyChanged(bool)));

    connect(ui->chkProtectionBlack, SIGNAL(clicked(bool)), this, SLOT(chkResistantChanged(bool)));
    connect(ui->chkProtectionBlue, SIGNAL(clicked(bool)), this, SLOT(chkResistantChanged(bool)));
    connect(ui->chkProtectionGreen, SIGNAL(clicked(bool)), this, SLOT(chkResistantChanged(bool)));
    connect(ui->chkProtectionRed, SIGNAL(clicked(bool)), this, SLOT(chkResistantChanged(bool)));
    connect(ui->chkProtectionTarget, SIGNAL(clicked(bool)), this, SLOT(chkResistantChanged(bool)));
    connect(ui->chkProtectionWhite, SIGNAL(clicked(bool)), this, SLOT(chkResistantChanged(bool)));

    connect(ui->PriceSelectWidget->txtPrice, SIGNAL(textChanged(QString)), this, SLOT(txtPriceChanged(QString)));

    connect(ui->btnExpand, SIGNAL(clicked()), this, SLOT(ExpandCustomText()));
    connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(SaveNewCard()));
}

void FormNewCard::SlotAddNewAdditionalAbility()
{
    form = new EditAdditionalAbilitiesForm(this);
    form->setWindowModality(Qt::ApplicationModal);
    if(form->exec() == 1)
    {
        ui->listWidgetAdditionalAbilities->addItem(form->getAdditionalAbilityText());
        // TODO just do it working!
        txtPriceChanged(form->getAdditionalAbilityText());
    }
}

void FormNewCard::SlotEditAdditionalAbility(QModelIndex index)
{
    AdditionalAbility *selectedAbility = new AdditionalAbility();
    selectedAbility->Init(ui->listWidgetAdditionalAbilities->item(index.row())->text());

    form = new EditAdditionalAbilitiesForm(this, selectedAbility);
    form->setWindowModality(Qt::ApplicationModal);

    if(form->exec() == 1)
    {
        ui->listWidgetAdditionalAbilities->item(index.row())->setText(form->getAdditionalAbilityText());
    }
}

void FormNewCard::cmbCardTypeChanged(QString value)
{
    setCardRootProperty("Type", value);

    if (ui->cmbCardType->currentIndex() == 1)
        ShowCreatureProperties(true);
    else if (ui->cmbCardType->currentIndex() == 7)
    {
        ShowCreatureProperties(true);
        ui->gbxProtects->setVisible(false);
        foreach(QObject * child, ui->gbxCreatrueProperties->children())
        {
            if (QString("QCheckBox").compare(child->metaObject()->className(), Qt::CaseInsensitive) == 0 )
            {
                ((QCheckBox *)child)->setEnabled(false);
                ((QCheckBox *)child)->setVisible(false);
            }
        }
        ui->chkTapped->setEnabled(true);
        ui->chkTapped->setVisible(true);
    }
    else
        ShowCreatureProperties(false);
}

void FormNewCard::spnDamageChanged(QString value)
{
    setCardRootProperty("Damage", value);
}

void FormNewCard::spnLifeChanged(QString value)
{
    setCardRootProperty("Life", value);
}

void FormNewCard::chkDamageXChanged(bool value)
{
    setCardRootProperty("Damage", (value?"1":0), "X");
}

void FormNewCard::chkLifeXChanged(bool value)
{
    setCardRootProperty("Life", (value?"1":0), "X");
}

void FormNewCard::chkPropertyChanged(bool value)
{
    QString propName = sender()->objectName();
    propName = propName.mid(3);
    if (value)
        setCardRootProperty(propName, NULL);
    else
        removeCardRootProperty(propName);
}

void FormNewCard::chkResistantChanged(bool value)
{
    QString propName = sender()->objectName();
    propName = propName.mid(13);
    addProtection(propName, value);
}

void FormNewCard::txtPriceChanged(QString price)
{
    price = price.trimmed();
    QDomDocument *doc = new QDomDocument();
    doc->setContent(ui->txtCustomText->toPlainText());
    QDomNodeList nodes = doc->elementsByTagName(WORD_CARD);

    QDomElement rootElement;
    if (nodes.isEmpty())
    {
        rootElement= doc->createElement(WORD_CARD);
        doc->appendChild(rootElement);
    }
    else
        rootElement = doc->documentElement();

    QDomDocument *docPrice = new QDomDocument();
    docPrice->setContent(price);
    QDomNode resultNode;

    if (rootElement.elementsByTagName(docPrice->documentElement().tagName()).count() > 0)
        resultNode = rootElement.removeChild(rootElement.elementsByTagName(docPrice->documentElement().tagName()).item(0));
    if (resultNode.isNull())
        resultNode = rootElement.removeChild(rootElement.elementsByTagName(docPrice->documentElement().tagName()).item(1));

    rootElement.appendChild(docPrice->documentElement());

    ui->txtCustomText->setText(doc->toString(4));
}

void FormNewCard::ExpandCustomText()
{
    QDialog *expandedText = new QDialog(this);
    QVBoxLayout layout;
    QTextEdit te;
    QPushButton btn;

    te.setText(ui->txtCustomText->toPlainText());
    btn.setText("Close");
    connect(&btn, SIGNAL(clicked()), expandedText, SLOT(close()));
    new XmlSyntaxHighlighter(te.document());

    layout.addWidget(&te);
    layout.addWidget(&btn);
    expandedText->setLayout(&layout);
    expandedText->setWindowState(Qt::WindowMaximized);
    expandedText->exec();
}

void FormNewCard::textCardNameChanged(QString value)
{
    setCardRootProperty(WORD_NAME, value);
}

void FormNewCard::textCardDescriptionChanged(QString value)
{
    setCardRootProperty(WORD_DESCRIPTION, value);
}

void FormNewCard::cmbCardSubTypeChanged(QString value)
{
    setCardRootProperty(WORD_SUBTYPE, value);
}

void FormNewCard::SaveNewCard()
{
    QDomDocument *doc = new QDomDocument();
    doc->setContent(ui->txtCustomText->toPlainText());
    card = CardPool::CreateCard(doc->documentElement());
    if (card == NULL)
        return;
    if (ui->cmbCardSubType->findText(card->getCardSubType()) == -1)
        ui->cmbCardSubType->addItem(card->getCardSubType());
}

void FormNewCard::setCardRootProperty(QString property, QString value, QString propName)
{
    value = value.trimmed();
    property = property.trimmed();
    QString curText = ui->txtCustomText->toPlainText();

    QDomDocument *doc = new QDomDocument();
    doc->setContent(curText);
    QDomNodeList nodes = doc->elementsByTagName(WORD_CARD);

    QDomElement rootElement;
    if (nodes.isEmpty())
    {
        rootElement= doc->createElement(WORD_CARD);
        doc->appendChild(rootElement);
    }
    else
        rootElement = doc->documentElement();


    nodes = doc->elementsByTagName(property);
    if (nodes.isEmpty())
    {
        QDomElement el = doc->createElement(property);
        if (!value.isEmpty())
            el.setAttribute(propName, value);
        rootElement.appendChild(el);
    }
    else
    {
        QDomElement el = nodes.item(0).toElement();
        if (!value.isEmpty())
            el.setAttribute(propName, value);
    }

    ui->txtCustomText->setText(doc->toString(4));

}

void FormNewCard::removeCardRootProperty(QString property)
{
    property = property.trimmed();
    QString curText = ui->txtCustomText->toPlainText();

    QDomDocument *doc = new QDomDocument();
    doc->setContent(curText);
    QDomNodeList nodes = doc->elementsByTagName(WORD_CARD);

    QDomElement rootElement;
    if (nodes.isEmpty())
        return;
    else
        rootElement = doc->documentElement();

    rootElement.removeChild(rootElement.elementsByTagName(property).item(0));

    ui->txtCustomText->setText(doc->toString(4));
}

void FormNewCard::addProtection(QString color, bool enabled)
{
    const QString PROP_NAME = "ProtectionOf";
    color = color.trimmed();

    QString curText = ui->txtCustomText->toPlainText();

    QDomDocument *doc = new QDomDocument();
    doc->setContent(curText);
    QDomNodeList nodes = doc->elementsByTagName(WORD_CARD);

    QDomElement rootElement;
    if (nodes.isEmpty())
    {
        rootElement= doc->createElement(WORD_CARD);
        doc->appendChild(rootElement);
    }
    else
        rootElement = doc->documentElement();


    nodes = doc->elementsByTagName(PROP_NAME);
    QDomElement el;
    if (nodes.isEmpty())
    {
        el = doc->createElement(PROP_NAME);
        rootElement.appendChild(el);
    }
    else
    {
        el = nodes.item(0).toElement();

    }

    if (enabled)
        el.appendChild(doc->createElement(color));
    else
        el.removeChild(el.elementsByTagName(color).item(0).toElement());

    ui->txtCustomText->setText(doc->toString(4));


}
